package com.zyf.cloud.services.userservice.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
public class MailConfig {

    //使用@Value得到application.properties中发件人邮箱地址信息
    @Value("${spring.mail.host}")
    private String mailHost;

    @Value("${spring.mail.port}")
    private int mailPort;

    @Value("${spring.mail.username}")
    private String mailUserName;

    @Value("${spring.mail.password}")
    private String mailPassword;

    private Properties javaMailProperties = new Properties();  //mail属性对象

    //1、创建JavaMailSenderImpl类的bean实例对象, 用于设置的是发件人的邮箱地址信息
    @Bean
    public JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        //不同类型的邮箱，它的host主机(SMTP服务器IP)、port端口是不一样的
        //如：阿里云邮箱的host为smtp.aliyun.com，port为465
        // 126邮箱的host为smtp.126.com，port为25
        //qq邮箱的host为smtp.qq.com，port为465
        //如果想使用诸如阿里云或126邮箱发邮件，一定要保证发件人的邮箱开通了SMTP服务。
        //注：只有开通了SMTP服务的邮箱才能使用javaMail技术发送邮件。
        mailSender.setHost(mailHost);
        mailSender.setPort(mailPort);
        //username为发件人邮箱账号
        mailSender.setUsername(mailUserName);
        //password为发件邮箱在开通SMTP服务后得到的授权密码(重点)
        mailSender.setPassword(mailPassword);
        mailSender.setDefaultEncoding("UTF-8");

        //设置SMTP服务器需要用户验证
        javaMailProperties.setProperty("mail.smtp.auth","true");
        javaMailProperties.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        javaMailProperties.setProperty("mail.smtp.socketFactory.port", "465");
        mailSender.setJavaMailProperties(javaMailProperties);
        return mailSender;
    }

    //2、创建SimpleMailMessage类的bean实例对象。 用来设置发送的邮件内容
    @Bean
    public SimpleMailMessage activationMailMessage() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(mailUserName);  //发件人邮箱账号
        simpleMailMessage.setSubject("【i旅行】请激活您的账户");
        return simpleMailMessage;
    }
}
